<template>
  <div class="login-container">
    <div class="loginhead" @click="qqq()">
      <div>{{ name }}被征地农民养老保险信息管理系统平台</div>
    </div>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">{{ name }}被征地农民养老保险信息管理系统平台</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>
      <div class="addmoudle">
        <el-checkbox v-model="checked" fill="#54c9f7">记住密码</el-checkbox>
        <span class="forget" style="cursor: pointer">忘记密码？</span>
      </div>
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
        >登录</el-button
      >
    </el-form>

    <div class="footerBox">
      <p>版权所有&nbsp;2018&nbsp;<span>杰立卡科技(北京)有限公司</span></p>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { getInfo, getInfotwo } from "@/api/user";
import { resetRouter } from "@/router";
import { ObjectName } from "../../../public/config";
export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("用户名不能为空"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error("密码最少为3位"));
      } else {
        callback();
      }
    };
    return {
      // ObjectName: this.GOLOBAL.ObjectName,
      name: "",
      loginForm: {
        username: "admin",
        password: "admin",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      checked: true, // 是否记住密码
      pathone: "",
      alength: "",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    // 密码明文密文切换
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    Md5JMone(pw) {
      return (pw = this.mdjm(pw)
        .substr(0, this.mdjm(pw).length - 4)
        .substring(3));
    },
    mdjm(str) {
      return this.$md5(
        (str = str
          .trim()
          .substr(0, str.length - 1)
          .substr(1)
          .split("")
          .reverse()
          .join(""))
      );
    },
    // 登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 密码进行MD5加密
          // this.loginForm.password = this.Md5JMone(this.loginForm.password)
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              localStorage.setItem("user", this.loginForm.username);
              if (this.loginForm.username == "admin") {
                this.$router.options.routes = JSON.parse(
                  localStorage.getItem("st")
                );
                localStorage.setItem(
                  "info",
                  JSON.stringify(this.$router.options.routes)
                );
                // this.$router.replace("/example/projectinfo");
                this.$router.replace("/welcome");
                // this.$router.replace({path:"/welcome",name: 'Welcome'});
                // this.$router.replace("/nested/projectinfo");
              } else {
                getInfo()
                  .then((res) => {
                    let routeList = res.ResList;
                    // let ary1 = []; // 二级路由
                    // routeList.forEach((item) => {
                    //   let data = { Mid: item.Id };
                    //   getInfotwo(data)
                    //     .then((res) => {
                    //       res.ResList.forEach((item) => {
                    //         ary1.push(item.ModelName);
                    //       });
                    //     })
                    //     .catch((err) => {
                    //       console.log(err);
                    //     })
                    //     .then((_) => {
                    //       // console.log(ary1);
                    //       sessionStorage.setItem("routesd", ary1);
                    //     });
                    // });
                    this.$store.dispatch(
                      "user/setRouterList",
                      JSON.stringify(routeList)
                    );
                    localStorage.setItem(
                      "routeList",
                      JSON.stringify(routeList)
                    );
                    localStorage.setItem("chang", 1);
                    this.loading = false;
                  })
                  .catch((err) => {
                    console.log(err);
                  })
                  .then((res) => {
                    let routeList = JSON.parse(
                      localStorage.getItem("routeList")
                    );
                    let ary1 = []; // 二级路由
                    this.aleng = routeList.length - 1;
                    routeList.forEach((item, index) => {
                      let data = { Mid: item.Id };
                      getInfotwo(data)
                        .then((res) => {
                          res.ResList.forEach((item) => {
                            ary1.push(item.ModelName);
                          });
                        })
                        .catch((err) => {
                          console.log(err);
                        })
                        .then((_) => {
                          // console.log(ary1);
                          sessionStorage.setItem("routesd", ary1);
                        })
                        .then((_) => {
                          if (this.aleng == index) {
                            this.$message.success("稍等,获取权限中...");
                            this.loading = true;
                            setTimeout((_) => {
                              this.login();
                              this.loading = false;
                            }, 1000);
                          }
                        });
                    });
                  });
              }
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    login() {
      let List = localStorage.getItem("routeList"),
        info = JSON.parse(localStorage.getItem("st")),
        ary1 = sessionStorage.getItem("routesd").split(",");
      // ary = [],
      // ary1 = sessionStorage.getItem("routesd").split(",");
      info.forEach((item) => {
        let aary = [];
        if (item.children) {
          item.children.forEach((i, index) => {
            if (ary1.includes(i.meta.title)) {
              aary.push(i);
            } else {
              i.hidden = true;
            }
            item.children = aary;
          });
          item.children.every((m) => m.hidden == true)
            ? (item.hidden = true)
            : (item.hidden = false);
        } else {
          item.hidden = true;
        }
      });
      localStorage.setItem("info", JSON.stringify(info));
      // const findItem = info.find(
      //   (item) => item.children != null && item.children.length != 0
      // );
      // console.log(findItem);
      // console.log(findItem.path);
      // let aaa = findItem.path;
      // this.$router.push({ path: aaa });
      this.$router.replace("/welcome");
    },
    infoHidden(e) {
      return (e.hidden = true);
    },
    trimSpace(array) {
      for (var i = 0; i < array.length; i++) {
        if (
          array[i] == " " ||
          array[i] == null ||
          typeof array[i] == "undefined"
        ) {
          array.splice(i, 1);
          i = i - 1;
        }
      }
      return array;
    },
    iterTree2(arr) {
      while (arr.some((item) => Array.isArray(item))) {
        arr = [].concat(...arr);
      }
      return arr;
    },
  },
  watch: {
    $route(to, from) {
      // this.$router.replace("/example/projectinfo");
      // location.reload()
    },
  },
  created() {
    this.name = ObjectName.name;
  },
  // 前置导航首位：登录之后跳转的不是首页的话就会阻塞跳转
  beforeRouteLeave(to, from, next) {
    // console.log(to.name);
    // console.log(from);
    // next();
    if (to.name == "WelcomeC") {
      next(true);
    }
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.loginhead {
  background-color: rgba(54, 53, 53, 0.6);
  color: #fff;
  text-align: left;
  line-height: 50px;
  height: 50px;
  overflow: hidden;
  > div {
    margin-left: 30px;
    font-weight: bold;
  }
}
.footerBox {
  width: 100%;
  position: fixed;
  bottom: 0;
  text-align: center;
  color: #fff;
  background-color: rgba(54, 53, 53, 0.6);
  > span {
    font-weight: 900;
  }
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 30px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  //
  .addmoudle {
    // width: 448px;
    height: 52px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    .forget {
      color: #606266;
      font-size: 15px;
    }
  }
}
</style>
